<script setup lang="ts">
import { ElMessage } from 'element-plus'
import EmojiTmp from './EmojiTmp.vue'
import { sendMsg } from '../utils/webSocketUtil'
import { useStore } from 'vuex'
import { checkIsFriend } from '../api/friend'

window.electron.ipcRenderer.on('clear-chat-input-content', () => {
  if (document.getElementById('textarea')) {
    document.getElementById('textarea')!.innerHTML = ''
  }
})

const store = useStore()

const props = defineProps({
  msgId: String,
  receiver: Number
})

const handleTransformEmoji = (emojiTag) => {
  if (document.getElementById('textarea')) {
    document.getElementById('textarea')!.innerHTML += emojiTag
  }
}

// 监听输入内容
let timer
const listenChatTextarea = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    if (timer) {
      ElMessage.warning('1秒内不能连续发送')
      event.preventDefault()
      return false
    }

    const sendMsgFunc = (): boolean => {
      let msg = ''
      if (document.getElementById('textarea')) {
        msg = document.getElementById('textarea')!.innerHTML
      }

      if (!inputIsEmpty(msg)) {
        ElMessage.warning('请输入内容')
        event.preventDefault()
        return false
      }

      if (props.receiver) {
        checkIsFriend(store.getters.getUserId, props.receiver)
          .then((res) => {
            if (res.code === 200) {
              if (!res.data) {
                ElMessage.error('你和对方不是好友关系')
                return false
              } else {
                sendMsg([props.msgId, 'text', props.receiver, msg], store)
                if (document.getElementById('textarea')) {
                  document.getElementById('textarea')!.innerHTML = ''
                }
                return true
              }
            } else return false
          })
          .catch((error) => {
            console.log('服务端异常:', error)
            ElMessage.error('服务端异常')
            return false
          })
      } else return false

      return true
    }

    if (!sendMsgFunc()) {
      event.preventDefault()
      return false
    }

    timer = setTimeout(() => {
      timer = null
    }, 1000)
    event.preventDefault()
  }

  // Shift + Ctrl 换行
  if (event.shiftKey && event.key === 'Enter') {
    event.preventDefault()
    if (window.getSelection()) {
      // const el = document.getElementById('textarea')
      const sel = window.getSelection()

      if (sel.rangeCount > 0) {
        const range = sel.getRangeAt(0).cloneRange()

        range.deleteContents()
        // 使用零宽度空格字符，视觉上不可见，解决光标后面插入第一个 br 不换行的问题
        const textNode = document.createTextNode('\u200B')
        range.insertNode(textNode)
        const br = document.createElement('br')
        range.insertNode(br)

        range.setStartAfter(br)
        range.collapse(true)

        sel.removeAllRanges()
        sel.addRange(range)
      }
    }
  }
  return
}

const inputIsEmpty = (msg) => {
  return msg.replace(/<br>|<br\s*\/?>|\u200B/g, '').trim() !== ''
}
</script>

<!--输入框-->
<template>
  <div class="p-2.5">
    <div class="h-7 max-h-7 w-full">
      <div class="w-6 h-6">
        <el-popover trigger="click" placement="bottom-start" width="450">
          <template #reference>
            <svg
              class="w-6 h-6 hover:cursor-pointer"
              viewBox="0 0 1024 1024"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M515.328 965.2224c-249.9072 0-453.2224-203.3152-453.2224-453.2224s203.3152-453.2224 453.2224-453.2224 453.2224 203.3152 453.2224 453.2224-203.3152 453.2224-453.2224 453.2224z m0-845.0048c-216.0128 0-391.7824 175.7696-391.7824 391.7824s175.7696 391.7824 391.7824 391.7824 391.7824-175.7696 391.7824-391.7824-175.7696-391.7824-391.7824-391.7824z"
                fill="#4f4f4f"
              ></path>
              <path
                d="M385.8944 409.4976m-53.6064 0a53.6064 53.6064 0 1 0 107.2128 0 53.6064 53.6064 0 1 0-107.2128 0Z"
                fill="#4f4f4f"
              ></path>
              <path
                d="M636.8768 409.4976m-53.6064 0a53.6064 53.6064 0 1 0 107.2128 0 53.6064 53.6064 0 1 0-107.2128 0Z"
                fill="#4f4f4f"
              ></path>
              <path
                d="M510.208 708.1984c-122.88 0-183.7568-103.1168-186.3168-107.52a30.72 30.72 0 0 1 53.1456-30.8224c1.9968 3.3792 46.4896 76.9024 133.1712 76.9024 86.784 0 131.328-73.7792 133.1712-76.9024a30.78144 30.78144 0 0 1 41.984-11.008 30.6688 30.6688 0 0 1 11.1616 41.8304c-2.56 4.352-63.488 107.52-186.3168 107.52z"
                fill="#4f4f4f"
              ></path>
            </svg>
          </template>
          <EmojiTmp @transform-emoji="handleTransformEmoji" />
        </el-popover>
      </div>
    </div>

    <div
      id="textarea"
      class="h-28 w-full text-left p-4 whitespace-normal overflow-x-hidden overflow-y-auto focus:outline-none"
      contenteditable
      autofocus
      @keydown="listenChatTextarea"
    ></div>
  </div>
</template>

<style scoped></style>
